package cn.ybk.org.service.impl;

import cn.ybk.basic.service.BaseService;
import cn.ybk.basic.service.impl.BaseServiceImpl;
import cn.ybk.basic.util.LoginContext;
import cn.ybk.basic.util.PageList;
import cn.ybk.org.domain.Department;
import cn.ybk.org.domain.Employee;
import cn.ybk.org.domain.Shop;
import cn.ybk.org.mapper.DepartmentMapper;
import cn.ybk.org.mapper.EmployeeMapper;
import cn.ybk.org.mapper.ShopMapper;
import cn.ybk.org.query.EmployeeQuery;
import cn.ybk.org.service.EmployeeService;
import cn.ybk.system.domain.Role;
import cn.ybk.system.mapper.RoleMapper;
import cn.ybk.user.domain.Logininfo;
import cn.ybk.user.mapper.LogininfoMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.annotation.ElementType;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
public class EmployeeServiceImpl extends BaseServiceImpl<Employee> implements EmployeeService {

    @Autowired
    private EmployeeMapper EmployeeMapper;

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Override
    @Transactional
    public void add(Employee Employee) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(Employee, logininfo);
        logininfo.setDisable(true);
        logininfo.setType(0);
        logininfoMapper.add(logininfo);
        Employee.setLogininfoId(logininfo.getId());
        Shop shop = LoginContext.getUserInfo().getShop();
        Employee.setShopId(shop.getId());
        EmployeeMapper.add(Employee);
        EmployeeMapper.addToEmpRole(Employee.getId(),Employee.getRoles());


    }

    @Override
    @Transactional
    public void delete(Long id) {
        Employee employee = EmployeeMapper.findById(id);
        Long logininfoId = employee.getLogininfoId();
        logininfoMapper.delete(logininfoId);
        EmployeeMapper.delete(id);
        EmployeeMapper.deleteToEmpRole(id);
    }

    @Override
    @Transactional
    public void update(Employee employee) {
        super.update(employee);
        EmployeeMapper.deleteToEmpRole(employee.getId());
        EmployeeMapper.addToEmpRole(employee.getId(), employee.getRoles());

    }

    @Override
    public List<Employee> drawer(Long id) {
        return EmployeeMapper.drawer(id);
    }

    @Override
    public List<Employee> list(Long id) {
        System.out.println(id);
        List<Employee> all = super.findAll();
        List<Employee> collect = all.stream().
                filter(employee -> Objects.nonNull(employee) && id.equals(employee.getShopId()))
                .collect(Collectors.toList());
        return collect;
    }
}
